<template>
  <div class="app-container">
    <avue-crud
      ref="crud"
      v-model="obj"
      :page="page"
      :data="tableData"
      :table-loading="tableLoading"
      :option="tableOption"
      :permission="permissionList"
      @on-load="getPage"
      @refresh-change="refreshChange"
      :before-open="beforeUpdate"
      @row-save="handleSave"
      @row-update="handleUpdate"
      @sort-change="sortChange"
      @search-change="searchChange"
      @selection-change="selectionChange"
    >
      <template slot-scope="scope" slot="areaList">
        {{ scope.row.fullAreaText }}
      </template>

      <template slot-scope="scope" slot="contractValidity">
        {{
          scope.row.startContractValidity +
          " 至 " +
          scope.row.endContractValidity
        }}
      </template>
      <template slot="state" slot-scope="scope">
        <el-tag
          size="mini"
          effect="dark"
          :type="
            scope.row.state == 0
              ? 'success'
              : scope.row.state == 1
              ? 'danger'
              : 'warning'
          "
        >
          {{ scope.row.$state }}
        </el-tag>
      </template>
      <template slot="stateForm" slot-scope="scope">
        <el-tag
          size="mini"
          effect="dark"
          :type="
            scope.row.state == 0
              ? 'success'
              : scope.row.state == 1
              ? 'danger'
              : 'warning'
          "
        >
          {{ scope.row.$state }}
        </el-tag>
      </template>

      <template slot-scope="scope" slot="areaListForm">
        <el-cascader
          ref="areaTree"
          v-if="operate !== 'view'"
          v-model="scope.row.areaList"
          :props="areaProps"
          @change="changeArea"
        ></el-cascader>
        <span v-if="operate === 'view'">{{ obj.fullAreaText }}</span>
      </template>

      <template slot-scope="scope" slot="contractValidityForm">
        <el-date-picker
          v-model="scope.row.contractValidity"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          @change="changeDate"
          value-format="yyyy-MM-dd"
        >
        </el-date-picker>
      </template>
    </avue-crud>
  </div>
</template>

<script>
import { checkPermi, checkRole } from "@/utils/permission";
import { getPage, addObj } from "@/api/book/organization";
import { getAll } from "@/api/book/organization";
import { tableOption } from "@/const/crud/book/organization";
import axios from "axios";
export default {
  name: "bookOrganization",
  computed: {
    permissionList() {
      return {
        addBtn: checkPermi(["book:organization:add"]),
        //editBtn: checkPermi(["book:organization:edit"]),
        viewBtn: checkPermi(["book:organization:get"]),
      };
    },
  },
  data() {
    let id = 0;
    return {
      obj: {},
      tableData: [],
      page: {
        total: 0, // 总页数
        currentPage: 1, // 当前页数
        pageSize: 20, // 每页显示多少条
      },
      paramsSearch: {},
      tableLoading: false,
      tableOption: tableOption,
      selectionData: [],
      areaOptions: [],
      areaProps: {
        value: "areaCode",
        label: "areaName",
        lazy: true,
        checkStrictly: true,
        lazyLoad: (node, resolve) => {
          const { level } = node;
          if (level === 0) {
            resolve([
              {
                areaCode: "100000",
                areaName: "全国",
                leaf: false,
              },
            ]);
          } else {
            let parentArea = node.value;
            this.getArea(parentArea, level === 4).then((res) => {
              resolve(res);
            });
          }
        },
      },
      operate: "",
    };
  },
  created() {},
  methods: {
    beforeUpdate(done, type) {
      this.operate = type;
      if (type !== "add") {
        let row = this.obj;
        this.obj.areaList = ["100000"];
        if (this.obj.provinceCode) {
          this.obj.areaList.push(this.obj.provinceCode);
        }
        if (this.obj.cityCode) {
          this.obj.areaList.push(this.obj.cityCode);
        }
        if (this.obj.areaCode) {
          this.obj.areaList.push(this.obj.areaCode);
        }
        if (this.obj.streetCode) {
          this.obj.areaList.push(this.obj.streetCode);
        }

        this.obj.contractValidity = [
          this.obj.startContractValidity,
          this.obj.endContractValidity,
        ];
      }
      done();
    },
    changeArea(val) {
      if (val.length) {
        let [countryCode, provinceCode, cityCode, areaCode, streetCode] = val;
        this.obj.countryCode = countryCode;
        this.obj.provinceCode = provinceCode;
        this.obj.cityCode = cityCode;
        this.obj.areaCode = areaCode;
        this.obj.streetCode = streetCode;
        this.$nextTick(() => {
          if (provinceCode) {
            this.obj.fullAreaText = this.$refs.areaTree.presentText
              .replaceAll(" / ", "")
              .replaceAll("全国", "");
          } else {
            this.obj.fullAreaText = "全国";
          }
        });
      }
    },
    changeDate(val) {
      this.obj.startContractValidity = val[0];
      this.obj.endContractValidity = val[1];
    },
    getArea(code, isLeaf) {
      return new Promise((resolve, reject) => {
        axios
          .get("/v3/config/district", {
            params: {
              keywords: code,
              subdistrict: 1,
              key: "5c5474605da0c21199de170e5f48c679",
            },
          })
          .then((res) => {
            let data = res.data.districts[0].districts.map((item) => {
              return {
                areaCode: item.level === "street" ? item.name : item.adcode,
                areaName: item.name,
                leaf: isLeaf,
              };
            });
            resolve(data);
          });
      });
    },
    getAreaTree(areaList) {
      areaList = areaList.slice(0, areaList.length - 1);
      return new Promise((resolve) => {
        Promise.all(
          areaList.map((code, index) => {
            return this.getArea(code, index === areaList.length - 1);
          })
        ).then((res) => {
          let data = {
            areaCode: "100000",
            areaName: "全国",
            leaf: false,
          };
          for (let i = 0; i < res.length; i++) {
            let child = res[res.length - 1 - i];
            if (res.length - 2 - i < 0) {
              break;
            }
            for (let j = 0; j < res[res.length - 2 - i].length; j++) {
              let parentItem = res[res.length - 2 - i][j];
              if (parentItem.areaCode === areaList[res.length - 1 - i]) {
                parentItem.children = child;
                break;
              }
            }
          }
          data.children = res;
          resolve(data);
        });
      });
    },
    selectionChange(list) {
      this.selectionData = list;
    },
    searchChange(params, done) {
      params = this.filterForm(params);
      this.paramsSearch = params;
      this.page.currentPage = 1;
      this.getPage(this.page, params);
      done();
    },
    sortChange(val) {
      let prop = val.prop
        ? val.prop.replace(/([A-Z])/g, "_$1").toLowerCase()
        : "";
      if (val.order == "ascending") {
        this.page.descs = [];
        this.page.ascs = prop;
      } else if (val.order == "descending") {
        this.page.ascs = [];
        this.page.descs = prop;
      } else {
        this.page.ascs = [];
        this.page.descs = [];
      }
      this.getPage(this.page);
    },
    getPage(page, params) {
      this.tableLoading = true;
      getPage(
        Object.assign(
          {
            pageNum: page.currentPage,
            pageSize: page.pageSize,
            descs: this.page.descs,
            ascs: this.page.ascs,
            appType: "2",
          },
          params,
          this.paramsSearch
        )
      )
        .then((response) => {
          this.tableData = response.rows;
          this.page.total = response.total;
          this.page.currentPage = page.currentPage;
          this.page.pageSize = page.pageSize;
          this.tableLoading = false;
        })
        .catch(() => {
          this.tableLoading = false;
        });
    },

    /**
     * @title 数据添加
     * @param row 为当前的数据
     * @param done 为表单关闭函数
     *
     **/
    handleSave: function (row, done, loading) {
      addObj(row)
        .then((data) => {
          this.$message({
            showClose: true,
            message: "添加成功",
            type: "success",
          });
          done();
          this.getPage(this.page);
        })
        .catch(() => {
          loading();
        });
    },
    /**
     * @title 数据更新
     * @param row 为当前的数据
     * @param index 为当前更新数据的行数
     * @param done 为表单关闭函数
     *
     **/
    handleUpdate: function (row, index, done, loading) {
      putObj(row)
        .then((data) => {
          this.$message({
            showClose: true,
            message: "修改成功",
            type: "success",
          });
          done();
          this.getPage(this.page);
        })
        .catch(() => {
          loading();
        });
    },
    /**
     * 刷新回调
     */
    refreshChange(page) {
      this.getPage(this.page);
    },
  },
};
</script>
